import React, { useEffect, useState } from 'react';
import { Table, Empty, Button, Typography, Spin } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { formatDateTime } from '@/utils/datetime';
import { getStatusTag } from '@/utils/status';
import { submissionService } from '@/services/submissionService';
import { problemService } from '@/services/problemService';
import SubmissionDetail from './SubmissionDetail';
import styles from './SubmissionList.module.css';
import { formatMemoryMB } from '@/utils/mappings';

const { Title } = Typography;

interface Submission {
  id: string;
  problem_id: number;
  problem_title: string;
  username: string;
  create_time: string;
  result: number;
  language: string;
  shared: boolean;
  statistic_info: {
    time_cost: number;
    memory_cost: number;
  };
  contest_id: number | null;
}

interface SubmissionListProps {
  problemId: number;
  onViewDetail?: (submissionId: string) => void;
}

const SubmissionList: React.FC<SubmissionListProps> = ({ problemId, onViewDetail }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Submission[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [problemTitle, setProblemTitle] = useState<string>('');
  const [loadingTitle, setLoadingTitle] = useState(false);

  // 获取题目标题
  useEffect(() => {
    const fetchProblemTitle = async () => {
      if (!problemId) return;
      
      try {
        setLoadingTitle(true);
        const response = await problemService.getProblem(problemId);
        
        if (response.data) {
          let problem = null;
          if ('data' in response.data) {
            problem = response.data.data;
          } else {
            problem = response.data;
          }
          
          if (problem && problem.title) {
            setProblemTitle(problem.title);
          }
        }
      } catch (error) {
        console.error('获取题目信息失败:', error);
      } finally {
        setLoadingTitle(false);
      }
    };
    
    fetchProblemTitle();
  }, [problemId]);

  const columns: ColumnsType<Submission> = [
    {
      title: '用户',
      dataIndex: 'username',
    },
    {
      title: '提交时间',
      dataIndex: 'create_time',
      render: (time: string) => formatDateTime(time),
    },
    {
      title: '状态',
      dataIndex: 'result',
      render: (result: number) => getStatusTag(result),
    },
    {
      title: '语言',
      dataIndex: 'language',
    },
    {
      title: '耗时',
      dataIndex: ['statistic_info', 'time_cost'],
      render: (time: number) => `${time} ms`,
    },
    {
      title: '内存',
      dataIndex: ['statistic_info', 'memory_cost'],
      render: (memory: number) => formatMemoryMB(memory),
    },
    onViewDetail && {
      title: '操作',
      key: 'action',
      render: (_: any, record: Submission) => (
        <Button 
          type="link" 
          size="small"
          onClick={() => onViewDetail(record.id)}
        >
          查看详情
        </Button>
      ),
    },
  ].filter(Boolean) as ColumnsType<Submission>;

  const fetchSubmissions = async (page = 1, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const response = await submissionService.getSubmissions({
        problem_id: problemId,
        page,
        limit: pageSize,
      });
      
      const data = response.data.data;
      setData(data.results);
      setPagination({
        ...pagination,
        current: data.current_page,
        total: data.count,
        pageSize: data.page_size,
      });
    } catch (error) {
      console.error('Failed to fetch submissions:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSubmissions();
  }, [problemId]);

  const handleTableChange = (newPagination: any) => {
    // 重新获取数据，传递新的页码和页面大小
    fetchSubmissions(newPagination.current, newPagination.pageSize);
  };

  if (!data.length && !loading) {
    return (
      <div className={styles.container}>
        {loadingTitle ? (
          <Spin size="small" />
        ) : (
          problemTitle && (
            <Title level={5} className={styles.problemTitle}>
              {problemTitle}
            </Title>
          )
        )}
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无提交记录"
          className={styles.emptyContent}
        />
      </div>
    );
  }

  return (
    <div className={styles.container}>
      {loadingTitle ? (
        <Spin size="small" />
      ) : (
        problemTitle && (
          <Title level={5} className={styles.problemTitle}>
            {problemTitle}
          </Title>
        )
      )}
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
        loading={loading}
        onChange={handleTableChange}
        className={styles.table}
        size="small"
        scroll={{ y: 'calc(100vh - 300px)' }}
        expandable={{
          expandedRowRender: (record) => (
            <SubmissionDetail
              submissionId={record.id}
              language={record.language}
            />
          ),
        }}
      />
    </div>
  );
};

export default SubmissionList; 